<svelte:options tag="ol-map" />

<link rel="stylesheet" href="./index.css" type="text/css">

<div bind:this={mapDom} class="map">
  <slot></slot>
</div>

<script>
  import { onMount } from 'svelte';

  import 'ol/ol.css';
  import Map from 'ol/Map.js';
  import TileLayer from 'ol/layer/Tile.js';
  import View from 'ol/View.js';
  import XYZ from 'ol/source/XYZ.js';
  import { fromLonLat } from 'ol/proj';

  export let center = '0,0';

  let map = null
  let mapDom;

  // 监听变化
  $: valueChanged(center);
  function valueChanged(newValue) {
    if(map){
      map.getView().setCenter(getCenter(newValue))
    }
  }

  // 事件
  function dispatchEvent(name, e) {
    const event = new CustomEvent(name, {
      detail: e,
      bubbles: true,
      cancelable: true,
      composed: true
    });
    mapDom.dispatchEvent(event);
  }

  function getCenter(center) {
    return center.split(',').map(Number)
  }
  // 生命周期函数
  onMount(() => {
    // map = new ol.Map({
    //   target: mapDom,
    //   layers: [
    //     new ol.layer.Tile({
    //       source: new ol.source.XYZ({
    //         url: 'https://gac-geo.googlecnapps.cn/maps/vt?lyrs=m&x={x}&y={y}&z={z}'
    //       })
    //     })
    //   ],
    //   view: new ol.View({
    //     center: ol.proj.fromLonLat(getCenter(center)),
    //     zoom: 4,
    //   })
    // });

    map = new Map({
      target: mapDom,
      layers: [
        new TileLayer({
          source: new XYZ({
            url: 'https://gac-geo.googlecnapps.cn/maps/vt?lyrs=m&x={x}&y={y}&z={z}'
          }),
        }),
      ],
      view: new View({
        center: fromLonLat(getCenter(center)),
        zoom: 4,
      }),
    });

    setTimeout(() => {
      dispatchEvent("mapload", map);
    }, 1000)

    map.on('moveend', e => {
      dispatchEvent("moveend", map);
    });
  });
</script>

<style lang="scss">
  .map {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
  }
</style>